using Autofac.Extensions.DependencyInjection;
using Autofac;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using SJ.Platform.EFCore.Model;
using SJ.Platform.Middleware.Middleware;
using System.Configuration;
using System.Net.Http;
using SJ.Platform.Extend.IOC;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(swgger => {
    swgger.SwaggerDoc("v1", new OpenApiInfo
    {
        Version = "v1",
        Title = "SJ.Platform.Api",
        Description = "数聚平台业务"
    });
    var apiXmlPath = Path.Combine(AppContext.BaseDirectory, "SJ.Platform.Api.xml");
    swgger.IncludeXmlComments(apiXmlPath, true);
    //权限认证
    swgger.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
    {
        Type = SecuritySchemeType.OAuth2,
        Flows = new OpenApiOAuthFlows
        {
            Password = new OpenApiOAuthFlow
            {
                TokenUrl = new Uri(builder.Configuration["IdentityServerUrl"] + "/connect/token"),
                Scopes = new Dictionary<string, string>
                {
                    { "SJ.Platform.Api", "数据平台业务" },
                    { "SJ.Platform.LogApi", "数据平台日志" },
                    { "SJ.Platform.StatisticsApi", "数据平台统计" }
                }
            }
        }
    });
    //权限认证
    swgger.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "oauth2"
                }
            },
            new string[] { }
        }
    });
});

builder.Services.AddAuthentication("Bearer")
                .AddJwtBearer(x =>
                 {
                     x.Authority = builder.Configuration["IdentityServerUrl"];//认证地址
                     x.TokenValidationParameters = new TokenValidationParameters { ValidateAudience = false };
                     x.RequireHttpsMetadata = false;
                 });
builder.Services.AddAuthorization(option =>
{
    option.AddPolicy("SJ.Platform.Api", builder =>
    {
        builder.RequireAuthenticatedUser();
        builder.RequireClaim("scope", "SJ.Platform.Api");
    });
});

//注册自定义配置
builder.Services.Configure<CustomConfig>(builder.Configuration.GetSection("CustomConfig"));

builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory())//Autofac依赖注入
.ConfigureContainer<ContainerBuilder>(container =>
{
    builder.Services.InitDependency(container, builder.Configuration);
});

//跨域
builder.Services.AddCors(options =>
{
    options.AddPolicy("CorsPolicy",
           builder => builder.WithOrigins("http://localhost:5173")
                             .AllowAnyMethod()
                             .AllowAnyHeader()
                             .AllowCredentials());
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.UseCors("CorsPolicy");
app.UseHttpsRedirection();
app.UseAuthentication();//权限认证
app.UseAuthorization();

//操作记录中间件
//app.UseMiddleware<OperationLogMiddleware>();

////异常处理中间件
app.UseMiddleware<ExceptionHandlingMiddleware>();

app.MapControllers();

app.Run();
